package webservices.sbe;
import java.text.SimpleDateFormat;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import webservices.alipaydirect.util.UtilDate;

import com.cb.domain.model.order.BOrder;
import com.cb.domain.model.order.Flight;
import com.cb.domain.model.order.Passenger;
import com.travelsky.sbeclient.exceptions.SBEClientException;
import com.travelsky.sbeclient.ispservice.InsuranceClient;
import com.travelsky.sbeclient.ispservice.request.Benefiter;
import com.travelsky.sbeclient.ispservice.request.BookPolicyRequest;
import com.travelsky.sbeclient.ispservice.request.CancelPolicyRequest;
import com.travelsky.sbeclient.ispservice.request.PolicyBean;
import com.travelsky.sbeclient.ispservice.request.Protecter;
import com.travelsky.sbeclient.ispservice.response.BookPolicyResponse;
import com.travelsky.sbeclient.ispservice.response.CancelPolicyResponse;
import com.travelsky.sbeclient.linkosky.exceptions.LinkoSkyException;
import com.travelsky.sbeclient.utils.Constants;

@Service
public class InsuranceSbeManager {
	private APITokenServices apiService=new APITokenServices();
	private final static Logger logger=Logger.getLogger(InsuranceSbeManager.class);
	private String token;
	private InsuranceClient client;
	
	/**
	 * 初始化Client
	 */
	private void initClient() {
		if (null == client) {
			client = new InsuranceClient();
		}
		apiService.createService(client);
		token = apiService.getToken();
	}
	/**
	 * 订购保险
	 * @param order
	 * @return
	 */
	public String booking(BOrder order,Passenger target)throws Exception{
		
		
		String policyId = null;
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		initClient();
		BookPolicyRequest sbeRequest = new BookPolicyRequest();
		sbeRequest.setDealNo(UtilDate.getOrderNum());
		PolicyBean policyBean = new PolicyBean();
		Benefiter[] benefiters = new Benefiter[1];
		Protecter[] protecters = new Protecter[1];
		Benefiter benefiter = new Benefiter();
		benefiter.setID(target.getCardNum());
		benefiter.setIDType("身份证");
		benefiter.setName("法定");
		benefiter.setRelation("法定");
		benefiters[0] = benefiter;
		
		Protecter protecter = new Protecter();
		protecter.setBirthday(df.format(target.getBirthday()));
		protecter.setID(target.getCardNum());
		protecter.setIDType("身份证");
		protecter.setName(target.getName());
		protecter.setRelation("本人");
		protecters[0] = protecter;

		
		policyBean.setBenefiters(benefiters);
		policyBean.setProtecters(protecters);
		Flight flight=null;
		Set<Flight> flights=order.getFlights();
		if(flights.size()>0){
			for(Flight temp:flights){
				flight=temp;
			}
		}
		policyBean.setAddress(order.getAddress());
		
		policyBean.setBirthday(df.format(target.getBirthday()));
		policyBean.setEmail(order.getContactEmail());
		policyBean.setFlightDate(flight.getDepDay()+" 00:00:00");
		policyBean.setFlightNo(flight.getCode());
		policyBean.setID(target.getCardNum());
		policyBean.setIDType("身份证");
		policyBean.setInsurancer(target.getName());
		policyBean.setNeedReceipt(true);
		policyBean.setPaperCount(1);
		policyBean.setPhone(order.getContact());
		policyBean.setPolicyType("A");
		policyBean.setPrice(20d);
		policyBean.setProductName("安达天下");
		policyBean.setStartDate(flight.getDepDay()+" 00:00:00");
		policyBean.setEndDate(flight.getArrDay()+" 00:00:00");
		policyBean.setZip(order.getContactCode());
		sbeRequest.setPolicyBean(policyBean);
		sbeRequest.setToken(apiService.getToken());
		BookPolicyResponse response = (BookPolicyResponse) client.bookPolicy(sbeRequest);
		if (response.getResultCode() == Constants.RESULT_CODE_SUCCEED) {
			policyId = ((BookPolicyResponse) response).getPolicyNo();
		}
		
		if(StringUtils.isNotEmpty(response.getErrorDescription().trim())){
			throw new Exception(response.getErrorDescription());
		}
		return policyId;
	}
	
	/**
	 * 取消保险
	 * @param policySbeId 保单号
	 * @return 1=不成功 0=成功
	 */
	public int cancel(String policySbeId){
		int res=1;
		if (StringUtils.isNotEmpty(policySbeId)) {
			CancelPolicyRequest request = new CancelPolicyRequest();
			request.setPolicyNo(policySbeId);
			request.setToken(token);
			try {
				CancelPolicyResponse response = (CancelPolicyResponse) client.cancelPolicy(request);
				if (response.getResultCode() == Constants.RESULT_CODE_SUCCEED) {
					logger.warn(((CancelPolicyResponse) response)
					.getResultCode());
					res=response.getResultCode();
				} else {
					logger.error(response.getErrorDescription());
				}
			} catch (SBEClientException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage(), e);
			}
		}
			return res;
	}
	
	 public static void main(String [] args){

	 }
}